// pages/menu-detail/menu-detail.js
const { menuManager } = require('../../data/menuManager.js');

Page({
  data: {
    menuId: '',
    menuName: '',
    menuInfo: {},
    dishes: [],
    filteredDishes: [],
    searchKeyword: '',
    selectedCategory: '全部',
    showCategoryFilter: true,
    categories: ['全部', '热菜', '凉菜', '主食', '汤类', '饮料', '甜品'],
    
    // 菜品编辑相关
    showDishEdit: false,
    editingDish: null,
    dishForm: {
      name: '',
      description: '',
      price: '',
      category: '热菜',
      tags: []
    },
    newTag: ''
  },

  onLoad(options) {
    const { menuId, menuName } = options;
    
    this.setData({
      menuId,
      menuName: decodeURIComponent(menuName || '菜单详情')
    });
    
    this.loadMenuData();
  },

  onShow() {
    // 每次显示时刷新数据
    this.loadMenuData();
  },

  // 加载菜单数据
  loadMenuData() {
    const { menuId } = this.data;
    
    try {
      let menuInfo, dishes;
      
      if (menuId === 'default') {
        // 加载默认菜单
        dishes = menuManager.loadDefaultMenu();
        menuInfo = {
          name: '默认菜单',
          description: '系统预设的通用菜单',
          icon: '🏠',
          type: '系统菜单',
          dishCount: dishes.length
        };
      } else {
        // 加载用户菜单
        const userMenus = wx.getStorageSync('userMenus') || [];
        const menu = userMenus.find(m => m.id === menuId);
        
        if (menu) {
          menuInfo = menu;
          dishes = menu.dishes || [];
        } else {
          wx.showToast({
            title: '菜单不存在',
            icon: 'none'
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
          return;
        }
      }
      
      this.setData({
        menuInfo,
        dishes,
        filteredDishes: dishes
      });
      
    } catch (error) {
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  // 搜索菜品
  onSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({
      searchKeyword: keyword
    });
    this.filterDishes();
  },

  // 清空搜索
  clearSearch() {
    this.setData({
      searchKeyword: ''
    });
    this.filterDishes();
  },

  // 选择分类
  selectCategory(e) {
    const category = e.currentTarget.dataset.category;
    this.setData({
      selectedCategory: category
    });
    this.filterDishes();
  },

  // 筛选菜品
  filterDishes() {
    const { dishes, searchKeyword, selectedCategory } = this.data;
    
    let filtered = dishes;
    
    // 按关键词筛选
    if (searchKeyword.trim()) {
      filtered = filtered.filter(dish => 
        dish.name.toLowerCase().includes(searchKeyword.toLowerCase()) ||
        (dish.description && dish.description.toLowerCase().includes(searchKeyword.toLowerCase()))
      );
    }
    
    // 按分类筛选
    if (selectedCategory !== '全部') {
      filtered = filtered.filter(dish => dish.category === selectedCategory);
    }
    
    this.setData({
      filteredDishes: filtered
    });
  },

  // 编辑菜单信息
  editMenu() {
    wx.showToast({
      title: '编辑菜单功能开发中',
      icon: 'none'
    });
  },

  // 添加菜品
  addDish() {
    this.setData({
      showDishEdit: true,
      editingDish: null,
      dishForm: {
        name: '',
        description: '',
        price: '',
        category: '热菜',
        tags: []
      },
      newTag: ''
    });
  },

  // 编辑菜品
  editDish(e) {
    const dish = e.currentTarget.dataset.dish;
    this.setData({
      showDishEdit: true,
      editingDish: dish,
      dishForm: {
        name: dish.name,
        description: dish.description || '',
        price: dish.price.toString(),
        category: dish.category,
        tags: dish.tags || []
      },
      newTag: ''
    });
  },

  // 隐藏菜品编辑弹层
  hideDishEdit() {
    this.setData({
      showDishEdit: false
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  },

  // 菜品名称输入
  onDishNameInput(e) {
    this.setData({
      'dishForm.name': e.detail.value
    });
  },

  // 菜品描述输入
  onDishDescInput(e) {
    this.setData({
      'dishForm.description': e.detail.value
    });
  },

  // 菜品价格输入
  onDishPriceInput(e) {
    this.setData({
      'dishForm.price': e.detail.value
    });
  },

  // 选择菜品分类
  selectDishCategory(e) {
    const category = e.currentTarget.dataset.category;
    this.setData({
      'dishForm.category': category
    });
  },

  // 标签输入
  onTagInput(e) {
    this.setData({
      newTag: e.detail.value
    });
  },

  // 添加标签
  addTag(e) {
    const tag = e.detail.value.trim();
    if (!tag) return;
    
    const { dishForm } = this.data;
    if (dishForm.tags.includes(tag)) {
      wx.showToast({
        title: '标签已存在',
        icon: 'none'
      });
      return;
    }
    
    this.setData({
      'dishForm.tags': [...dishForm.tags, tag],
      newTag: ''
    });
  },

  // 移除标签
  removeTag(e) {
    const tag = e.currentTarget.dataset.tag;
    const { dishForm } = this.data;
    
    this.setData({
      'dishForm.tags': dishForm.tags.filter(t => t !== tag)
    });
  },

  // 保存菜品
  saveDish() {
    const { dishForm, editingDish, menuId } = this.data;
    
    // 验证表单
    if (!dishForm.name.trim()) {
      wx.showToast({
        title: '请输入菜品名称',
        icon: 'none'
      });
      return;
    }
    
    if (!dishForm.price || isNaN(parseFloat(dishForm.price))) {
      wx.showToast({
        title: '请输入有效价格',
        icon: 'none'
      });
      return;
    }
    
    try {
      const dishData = {
        id: editingDish ? editingDish.id : 'dish_' + Date.now(),
        name: dishForm.name.trim(),
        description: dishForm.description.trim(),
        price: parseFloat(dishForm.price),
        category: dishForm.category,
        tags: dishForm.tags,
        image: editingDish ? editingDish.image : null
      };
      
      if (menuId === 'default') {
        wx.showToast({
          title: '默认菜单不能编辑',
          icon: 'none'
        });
        return;
      }
      
      // 更新用户菜单
      const userMenus = wx.getStorageSync('userMenus') || [];
      const menuIndex = userMenus.findIndex(m => m.id === menuId);
      
      if (menuIndex === -1) {
        wx.showToast({
          title: '菜单不存在',
          icon: 'none'
        });
        return;
      }
      
      if (editingDish) {
        // 编辑现有菜品
        const dishIndex = userMenus[menuIndex].dishes.findIndex(d => d.id === dishData.id);
        if (dishIndex !== -1) {
          userMenus[menuIndex].dishes[dishIndex] = dishData;
        }
      } else {
        // 添加新菜品
        if (!userMenus[menuIndex].dishes) {
          userMenus[menuIndex].dishes = [];
        }
        userMenus[menuIndex].dishes.push(dishData);
      }
      
      // 更新菜品数量
      userMenus[menuIndex].dishCount = userMenus[menuIndex].dishes.length;
      
      // 保存到本地存储
      wx.setStorageSync('userMenus', userMenus);
      
      // 刷新数据
      this.loadMenuData();
      
      this.hideDishEdit();
      
      wx.showToast({
        title: editingDish ? '保存成功' : '添加成功',
        icon: 'success'
      });
      
    } catch (error) {
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      });
    }
  },

  // 导出菜单
  exportMenu() {
    wx.showToast({
      title: '导出功能开发中',
      icon: 'none'
    });
  }
});
